(function($) {
	function bindCheckBoxEvent($table){
		$table.delegate("thead th input[type=checkbox]","change",function() {
			//event.preventDefault();
			var set = $table.find("tbody tr input[type=checkbox]");
            var checked = $(this).is(":checked");
            $(set).each(function() {
                if (checked) {
                    $(this).prop("checked", true);
                    $(this).parents('tr').addClass("active");
                } else {
                    $(this).prop("checked", false);
                    $(this).parents('tr').removeClass("active");
                }
            });
        });
		$table.delegate("tbody tr input[type=checkbox]","change",function() {
			//event.preventDefault();
            $(this).parents('tr').toggleClass("active");
            var set = $table.find("tbody tr input[type=checkbox]");
            var checkedSize = set.filter(":checked").length;
            var $checkAll = $table.find("thead th input[type=checkbox]");
            if(checkedSize==set.length){
            	$checkAll.prop("checked", true);
            } else {
            	$checkAll.prop("checked", false);
            }
        });
	}
	
	$.m.system = {
	    organization : {
	        initSelectForm : function(organizationFormName, positionFormName, isAuthSelect) {
	            var organizationTreeId = $.m.zTree.initSelectTree({
	                zNodes : [],
	                nodeType : "default",
	                fullName:true,
	                urlPrefix : _ctx + "/system/organization/organization",
	                async : true,
	                asyncLoadAll : true,
	                onlyDisplayShow: false,
	                lazy : true,
	                select : {
	                    btn : $("#selectOrganizationTree,#organizationName"),
	                    id : "organizationId",
	                    name : "organizationName",
	                    includeRoot: true
	                },
	                autocomplete : {
	                    enable : true
	                }
	            });

	            var positionTreeId = $.m.zTree.initSelectTree({
	                zNodes : [],
	                urlPrefix : _ctx + "/system/organization/position",
	                async : true,
	                asyncLoadAll : true,
	                onlyDisplayShow: false,
	                lazy : true,
	                select : {
	                    btn : $("#selectPositionTree,#positionName"),
	                    id : "positionId",
	                    name : "positionName",
	                    includeRoot: true
	                },
	                autocomplete : {
	                    enable : true
	                },
	                setting :{
	                    check : {
	                        enable:true,
	                        chkStyle:"checkbox",
	                        chkboxType: { "Y": "", "N": "s" }
	                    }
	                }
	            });

	            $(".btn-add-organization").click(function() {
	                var organizationId = $("#organizationId").val();
	                var positionId = $("#positionId").val();

	                if(isAuthSelect) {
	                    if(!organizationId && !positionId) {
	                        $.m.app.alert($.i18n.system.atLeastChooseOneOrganizationAndPosition);
	                        return;
	                    }
	                } else {
	                    if(!organizationId) {
	                        $.m.app.alert($.i18n.system.chooseOrganization);
	                        return;
	                    }
	                    if(!positionId) {
	                        $.m.app.alert($.i18n.system.choosePosition);
	                        return;
	                    }
	                    if($("#organizationId_" + organizationId).length > 0) {
	                    	$.m.app.alert($.i18n.system.alreadyChose);
	                    	return;
	                    }
	                }
	                
	                var organizationName = $("#organizationName").val();
	                var positionName = $("#positionName").val();

	                var template =
	                    "<tr>" +
	                        "<td class='check'><label class='mt-checkbox mt-checkbox-single mt-checkbox-outline'><input type='checkbox' class='checkboxes'><span class='text'></span></label></td>" +
	                        "<td>" +
	                        "<input type='hidden' id='organizationId_{organizationId}' name='{organizationFormName}' value='{organizationId}'>" +
	                        "{organizationName}" +
	                        "</td>" +
	                        "<td>" +
	                        "<input type='hidden' name='{positionFormName}' value='{positionId}'>" +
	                        "{positionName}" +
	                        "</td>" +
	                        "<td>" +
	                        "<a class='btn btn-link btn-edit btn-delete-organization' href='javascript:;' onclick='$.m.system.organization.removeOrganization(this);'><i class='icon-trash'></i></a>" +
	                        "</td>" +
	                        "</tr>";
	                $("#selectedOrganization .table tbody").append(
	                    template.replace(/{organizationId}/g, organizationId)
	                        .replace("{organizationName}", organizationName.replace(">", "&gt;").replace(/,/g, "<br/>"))
	                        .replace("{positionId}", positionId)
	                        .replace("{positionName}", positionName.replace(">", "&gt;").replace(/,/g, "<br/>"))
	                        .replace("{organizationFormName}", organizationFormName)
	                        .replace("{positionFormName}", positionFormName)
	                );
	                var positionTree = $.fn.zTree.getZTreeObj(positionTreeId);
	                if(positionTree) positionTree.checkAllNodes(false);
	                var organizationTree = $.fn.zTree.getZTreeObj(organizationTreeId)
	                if(organizationTree) organizationTree.checkAllNodes(false);
	                $("#organizationId,#organizationName,#positionId,#positionName").val("");
	            });

	            bindCheckBoxEvent($("#selectedOrganization table"));

	            $(".btn-delete-all-organization").click(function() {
	                var checkbox = $("#selectedOrganization table").find("tbody :checkbox:checked");
	                if(!checkbox.length) {
	                    return;
	                }
	                $.m.app.confirm({
	                    title : $.i18n.confirmToDelete,
	                    message : $.i18n.confirmToDeleteSelection,
	                    ok : function() {
	                        checkbox.each(function() {
	                            $(this).prop("checked", false).change();//触发取消全选
	                            $(this).closest("tr").remove();
	                        });
	                    }
	                });

	            });
	        },
	        removeOrganizationBtn : function() {
	            $("#selectOrganization").remove();
	            $(".btn-delete-organization").remove();
	            $(".btn-delete-all-organization").remove();
	        },
	        removeOrganization : function(a) {
	            $.m.app.confirm({
	                message : $.i18n.confirmToDelete,
	                ok : function() {
	                	$(a).closest('tr').find(":checkbox").prop("checked", false).change();//触发取消全选
	                    $(a).closest('tr').remove();
	                }
	            });
	        }
	    },
	    user : {
	        initValidator : function(form) {
	            var ajaxCall = {
	                "url": _ctx + "/system/account/user/ajaxValidate.html",
	                //动态提取的数据。验证时一起发送
	                extraDataDynamic: ['#id'],
	                //验证失败时的消息
	                //"alertText": "* 该名称已被其他人使用",
	                //验证成功时的消息
	                //"alertTextOk": "该名称可以使用",
	                "alertTextLoad": "* 正在验证，请稍等。。。"
	            };
	            //自定义ajax验证  ajax[ajaxNameCall] 放到验证规则的最后（放到中间只有当submit时才验证）
	            //不能合并到一个 否则提交表单时有个黑屏阶段
	            $.validationEngineLanguage.allRules.ajaxCall = ajaxCall;
	            $.validationEngineLanguage.allRules.loginName = {
	            		"regex": /^[_a-zA-Z][_\w]{1,19}$/,
	            		"alertText": "* 2到20个字母、数字或下划线组成，且必须以非数字开头"
	            };
	            $.validationEngineLanguage.allRules.name = {
	            		"regex": /^[\u4E00-\u9FA5\uf900-\ufa2d_a-zA-Z][\u4E00-\u9FA5\uf900-\ufa2d_\w]{1,19}$/,
	            		"alertText": "* 2到20个汉字、字母、数字或下划线组成，且必须以非数字开头"
	            };
	            $.validationEngineLanguage.allRules.mobile = {
	                "regex": /^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/,
	                "alertText": "* 手机号错误"
	            };
	            var validationEngine = form.validationEngine();
	            return validationEngine;
	        },
	        initUserListButton : function() {
	            $(".change-password").click(function() {
	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) return;
	                var id = checkbox.val();
	                var url = _ctx + "/system/account/user/changePassword.html?" + checkbox.serialize();

	                var model = $.m.app.confirm({
	                    title: "修改密码",
	                    message : "请输入新密码：<br/><input type='password' id='password' class='input-medium'/>",
	                    ok : function() {
	                        var password = $("#password").val();
	                        if(password) {
	                            window.location.href = url + "&newPassword=" + password;
	                        }
	                    }
	                });
	            });

	            $(".block-user,.unblocked-user").click(function() {
	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) return;
	                var id = checkbox.val();
	                var status = $(this).is(".unblocked-user") ? "true" : "false";
	                var url = _ctx + "/system/account/user/changeStatus.html?activated=" + status + "&" + checkbox.serialize();

	                var title = status == 'false' ? "冻结用户" : "激活用户";
	                var tip = status == 'false' ? "请输入冻结原因:" : "请输入激活原因：";

	                $.m.app.confirm({
	                    title: title,
	                    message : tip + "<br/><textarea id='reason' style='width: 300px;height: 50px;'></textarea>",
	                    ok : function() {
	                        var reason = $("#reason").val();
	                        if(reason) {
	                            window.location.href = url + "&reason=" + reason;
	                        }
	                    }
	                });
	            });
	            $(".status-history").click(function() {
	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) return;
	                var ids = $.m.app.joinVar(checkbox.val());
	                var url = _ctx + "/system/account/user/statusHistory?search.user.id_eq=" + ids;

	                $.m.app.modalDialog("状态改变历史", url, {width : 800});
	            });
	            $(".last-online-info").click(function() {

	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) return;
	                var ids = $.m.app.joinVar(checkbox.val());
	                var url = _ctx + "/system/account/user/lastOnline?search.userId_eq=" + ids;

	                $.m.app.modalDialog("最后在线历史", url, {width : 800});
	            });


	            $(".recycle").click(function() {

	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) return;

	                var url = _ctx + "/system/account/user/recycle.html?" + checkbox.serialize();
	                $.m.app.confirm({
	                    title : "还原删除的用户",
	                    message : "确认还原吗？",
	                    ok : function() {
	                        window.location.href = url;
	                    }
	                });
	            });

	        },

	        initOnlineListButton : function() {
	            $(".btn-force-logout").click(function() {
	                var checkbox = $.m.table.getAllSelectedCheckbox($(".table"));
	                if(!checkbox.length) {
	                    return;
	                }
	                $.m.app.confirm({
	                	title : "强制退出",
	                    message : "确认强制退出吗？",
	                    ok : function() {
	                        var url = _ctx + "/system/account/user-online/forceLogout.html?" + checkbox.serialize();
	                        window.location.href = url;
	                    }
	                });
	            });
	        }
	    },
	    auth : {
	    	initSelectPermission : function(){
	    		$.m.zTree.initSelectTree({
			        zNodes : [],
			        nodeType : "default",
			        fullName:true,
			        urlPrefix : _ctx + "/system/privilege/permission",
			        async : true,
			        asyncLoadAll : true,
			        onlyDisplayShow: true,
			        lazy : false, 
			        select : {
			            btn : $("#selectPermissionTree,#permissionName"),
			            id : "permissionId",
			            name : "permissionName",
			            includeRoot: true
			        },
			        autocomplete : {
			            enable : true
			        },
			        setting :{
			            check : {
			                enable:true,
			                chkStyle:"checkbox",
			                // chkboxType: { "Y": "", "N": "s" },
                            chkboxType: { "Y" : "ps", "N" : "ps" }, // 选中时关联父，关联子，取消时关联父，关连子
			                onlyCheckLeaf : false,
			                onlySelectLeaf : false
			            }
			        }
			    });
				
			    $("#permissionName").change(function() {
			        $("#selectedPermissionName").val($(this).val().replace(/,/g, "\n"));
			    });
	    	},
	        initSelectRole : function(selectedData) {
	        	$.m.form.initDualListbox($('#roleIds'), {
	            	nonSelectedListLabel: $.i18n.system.nonSelectedRoleList,
	    			selectedListLabel: $.i18n.system.selectedRoleList,
	            	selectedData : selectedData
	            });
	        },
	        initSelectOrganization : function(){
	    		$.m.zTree.initSelectTree({
			        zNodes : [],
			        nodeType : "default",
			        fullName:true,
			        urlPrefix : _ctx + "/system/organization/organization",
			        async : true,
			        asyncLoadAll : true,
			        onlyDisplayShow: true,
			        lazy : false, 
			        select : {
			            btn : $("#selectOrganizationTree,#organizationName"),
			            id : "organizationId",
			            name : "organizationName",
			            includeRoot: true
			        },
			        autocomplete : {
			            enable : true
			        },
			        setting :{
			            check : {
			                enable:true,
			                chkStyle:"checkbox",
			                chkboxType: { "Y": "", "N": "s" },
			                onlyCheckLeaf : false,
			                onlySelectLeaf : false
			            }
			        }
			    });
				
			    $("#organizationName").change(function() {
			        $("#selectedOrganizationName").val($(this).val().replace(/,/g, "\n"));
			    });
	    	}
	    }
	};
})(jQuery);